package com.itheima.controller;

import com.itheima.common.constant.MessageConstant;
import com.itheima.common.entity.Result;
import com.itheima.common.utils.SMSUtils;
import com.itheima.common.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/validatecode")
@Slf4j
public class ValidatecodeController {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 发送短信验证码
     * @param telephone
     * @return
     */
    @PostMapping("/send4Order")
    public Result send4Order(String telephone) {
        log.info("手机号码为：{}", telephone);
        // 生成验证码
        String code = ValidateCodeUtils.generateValidateCode(6) + "";
        // 发送短信
        SMSUtils.sendMessage(SMSUtils.VALIDATE_CODE, telephone,code);
        // 将验证码保存到redis,有效期5分钟
        redisTemplate.opsForValue().set(telephone + "Order",code,5, TimeUnit.MINUTES);
        return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }

    /**
     * 发送短信验证码
     * @param telephone
     * @return
     */
    @GetMapping("/send4Login")
    public Result send4Login(String telephone) {
        log.info("手机号码为：{}", telephone);
        // 生成验证码
        String code = ValidateCodeUtils.generateValidateCode(6) + "";
        // 发送短信
        SMSUtils.sendMessage(SMSUtils.VALIDATE_CODE, telephone,code);
        // 将验证码保存到redis,有效期5分钟
        redisTemplate.opsForValue().set(telephone + "Login",code,5, TimeUnit.MINUTES);
        return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }
}
